# -*- coding: utf-8 -*-
#
# Author:: JonnyHan
# Date:: 2020/10/15
import os
from time import sleep

from config import constants
from submodules.common.lib.log_ import logger




def start(package_name, activity_name):
    cmd_tmp = f"adb shell am start {package_name}/{activity_name}"
    cmd_tmp = "adb shell am start com.gbits.atm.leiting/com.leiting.sdk.activity.PrivacyActivity"
    logger.info(f"cmd_tmp:{cmd_tmp}")
    os.popen(cmd_tmp)


def kill(package_name):
    cmd_tmp = f"adb shell am force-stop {package_name}"
    logger.info(f"cmd_tmp:{cmd_tmp}")
    os.popen(cmd_tmp)


def is_adb_ready():
    res_list = os.popen("adb --version").readlines()
    if len(res_list) > 0:
        logger.info("ADB is ready")
        logger.info(res_list[0].strip())
        return True
    else:
        logger.info("cmd res:%s" % str(res_list))
        raise Exception("adb命令不可用")
        # return False


def get_device_list():
    '''
    [[${serial number,${status}}],[...]]
    '''
    device_list = []
    res = os.popen("adb devices")
    res_list = res.readlines()[:-1][1:]
    for item in res_list:
        tmp_list = item.strip().split("\t")
        if tmp_list[1] != "offline":
            device_list.append(tmp_list)
    return device_list


# def is_device_ready():
#     if is_adb_ready():
#         if len(get_device_list()) > 0:
#             return True
#         else:
#             logger.error("adb devices列表为空")
#             raise Exception("adb devices列表为空")
#             # return False


def get_adb_devices_ready():
    while True:
        device_list = get_device_list()
        if len(device_list) > 0:
            logger.info("ADB devices is ready.")
            return device_list
        else:
            kill(constants.PACKAGE_NAME_WENDAO)
            start(constants.PACKAGE_NAME_WENDAO, constants.ACTIVITY_NAME_WENDAO_MAIN)
            sleep(5)
            res = os.popen("sudo killall adbd").read()
            logger.info(f"{res}")
            res = os.popen("adb kill-server").read()
            logger.info(f"{res}")
            res = os.popen("adb start-server").read()
            logger.info(f"{res}")


if __name__ == "__main__":
    def get_device_list_test():
        res = get_device_list()
        print(res)


    def get_device_list_test():
        res = get_device_list()
        print(res)


    def test_get_devices_adb_ready():
        res = get_adb_devices_ready()
        print(res)


    test_get_devices_adb_ready()
